# libs ----
library(sf)
library(geomander)
library(tidyverse)
library(redist)
library(ppmf)
library(grid)
library(patchwork)
library(wacolors)


# helper ----
source('../00_custom_functions.R')

# data ----
state <- "MS"

ppmf19 <- read_ppmf(state, "../../data-raw/ppmf_19.csv")
ppmf12 <- read_ppmf(state, "../../data-raw/ppmf_12.csv")
ppmf4 <- read_ppmf(state, "../../data-raw/ppmf_04.csv")

ppmf19 <- ppmf19 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf19) <- paste("v19", colnames(ppmf19), sep = "_")
ppmf19 <- ppmf19 %>% rename(GEOID = v19_GEOID)

ppmf12 <- ppmf12 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf12) <- paste("v12", colnames(ppmf12), sep = "_")
ppmf12 <- ppmf12 %>% rename(GEOID = v12_GEOID)

ppmf4 <- ppmf4 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf4) <- paste("v4", colnames(ppmf4), sep = "_")
ppmf4 <- ppmf4 %>% rename(GEOID = v4_GEOID)

# comparison ----
census <- create_block_table(state = 'MS')

# all joined ----
block <- census %>%
  left_join(ppmf12, by = 'GEOID') %>%
  left_join(ppmf4, by = 'GEOID') %>% 
  left_join(ppmf19, by = "GEOID")

# and remove duplicates
block <- block %>% select(-contains('.'))
# and set missing block pop/vap to 0
block[is.na(block)] <- 0
# add block_group back (dropped by contains('.'))
block <- block %>% breakdown_geoid()

# get precincts set up:
prec2010 <- st_read('../../data/MS/precincts_2010/SW_VTD10.shp')
msDist <- st_read('../../data/MS/Sen_2010_TRP1/Sen_2010_TRP1.shp') %>% arrange(Distnum)
msDist <- msDist %>% st_transform(4269)

sf::sf_use_s2(FALSE)
block_prec_match <- geo_match(from = block, to = prec2010, method = 'area')
block_dist_match <- geo_match(from = block, to = msDist, method = 'area')
prec_dist_match <- geo_match(from = prec2010, to = msDist, method = 'area')

# block level parity = 0.04890343
redist.parity(block_dist_match, block$pop)

# agg block 2 prec
block$prec <- block_prec_match
ppmf_at_prec <- ppmf_block2prec(block, prec)

# join them together
ms <- prec2010 %>%
  mutate(prec = row_number()) %>%
  left_join(ppmf_at_prec, by = 'prec')

ms <- ms %>% mutate(sld_up = prec_dist_match)

saveRDS(object = ms, file = '../../data/MS/ms.Rds')
